import {
  WebSocketGateway,
  SubscribeMessage,
  MessageBody,
  WebSocketServer,
} from '@nestjs/websockets';
import { ChatroomService } from './chatroom.service';
import { CreateChatroomDto } from './dto/create-chatroom.dto';
import { UpdateChatroomDto } from './dto/update-chatroom.dto';
import { Server, Socket } from 'socket.io';

@WebSocketGateway()
export class ChatroomGateway {
  constructor(private readonly chatroomService: ChatroomService) {}

  @WebSocketServer()
  server: Server;

  @SubscribeMessage('joinRoom')
  joinRoom(client: Socket, payload) {
    console.log(payload.roomName);
    client.join(payload.roomName);
    this.server.to(payload.roomName).emit('message', {
      nickName: payload.nickName,
      message: `${payload.nickName} 加入了 ${payload.roomName} 房间`,
    });
  }

  @SubscribeMessage('sendMessage')
  sendMessage(@MessageBody() payload: any): void {
    console.log(payload);
    this.server
      .to(payload.room)
      .emit('message', {
        nickName: payload.nickName,
        message: payload.message,
      });
  }

  @SubscribeMessage('createChatroom')
  create(@MessageBody() createChatroomDto: CreateChatroomDto) {
    return this.chatroomService.create(createChatroomDto);
  }

  @SubscribeMessage('findAllChatroom')
  findAll() {
    return this.chatroomService.findAll();
  }

  @SubscribeMessage('findOneChatroom')
  findOne(@MessageBody() id: number) {
    return this.chatroomService.findOne(id);
  }

  @SubscribeMessage('updateChatroom')
  update(@MessageBody() updateChatroomDto: UpdateChatroomDto) {
    return this.chatroomService.update(updateChatroomDto.id, updateChatroomDto);
  }

  @SubscribeMessage('removeChatroom')
  remove(@MessageBody() id: number) {
    return this.chatroomService.remove(id);
  }
}
